package com.superb.gateway.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.superb.common.core.model.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Order(-1)：优先加载该处理器
 * RequiredArgsConstructor使处理器可以通过参数构造的方式注入到spring
 * @Author: ajie
 * @CreateTime: 2024-04-23 16:32
 */
@Slf4j
@Order(-1)
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper;

    /**
     * 全局异常处理类
     * @param exchange
     * @param ex
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 判断响应是否结束，多个异常处理时
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 设置响应头类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result<Boolean> result = Result.error(500, ex.getMessage());
        // 设置响应状态码
        if (ex instanceof ResponseStatusException e) {
            response.setStatusCode(e.getStatusCode());
            result.setCode(e.getStatusCode().value());
        }
        if (ex instanceof SaTokenException exception) {
            if (exception.getCause() instanceof NotLoginException e) {
                result.setMessage(e.getMessage());
                result.setCode(e.getCode());
            }
        }
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                log.warn("Error Spring Cloud Gateway : {} {}", exchange.getRequest().getPath(), ex.getMessage());
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            } catch (JsonProcessingException e) {
                log.error("Error writing response", ex);
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
